var location = require('location');
var iot = require('iot');
var network = require('network');

var net = network.openNetWorkClient();

var loc = location.open();

var productKey = "productKey";
var deviceName = "deviceName";
var deviceSecret = "deviceSecret";

var device;

/**
 * location function
*/
var bts;
var nearbts;
function lbs_location()
{
    var mcc = loc.getAccessedLbsInfo().mcc;
    var mnc = loc.getAccessedLbsInfo().mnc;
    var cellid = loc.getAccessedLbsInfo().cellid;
    var lac = loc.getAccessedLbsInfo().lac;
    var signal = loc.getAccessedLbsInfo().signal;

    console.log('mcc ' + mcc + ' mnc ' + mnc + ' cellid ' + cellid + ' lac ' + lac + ' signal ' + signal);
    bts = mcc + ',' + mnc + ',' + lac + ',' + cellid + ',' + signal;
    nearbts = mcc + ',' + mnc + ',' + lac + ',' + cellid + ',' + signal;

    console.log('bts is ' + bts);
    console.log('neartbts ' + nearbts);
}

function createDevice() {
    device = iot.device({
        productKey: productKey,
        deviceName: deviceName,
        deviceSecret: deviceSecret,
        region: 'cn-shanghai'
    });

    device.on('connect', function() {
        console.log('success connect to aliyun');
        onConnect();
    });

    /* 网络断开事件 */
    device.on('disconnect', function () {
        console.log('disconnect ');
    });

    /* 关闭连接事件 */
    device.on('close', function () {
        console.log('iot client just closed');
    });

    /* 发生错误事件 */
    device.on('error', function (err) {
        console.log('error ' + err);
    });

    /* 云端设置属性事件 */
    device.onProps(function (res) {
        console.log('cloud req msg_id is ' + res.msg_id);
        console.log('cloud req params_len is ' + res.params_len);
        console.log('cloud req params is ' + res.params);
    });

    /* 云端下发服务事件 */
    device.onService(function (res) {
        console.log('received cloud msg_id is ' + res.msg_id);
        console.log('received cloud service_id is ' + res.service_id);
        console.log('received cloud params_len is ' + res.params_len);
        console.log('received cloud params is ' + res.params);
    });
}

function onConnect() {
    setInterval(function () {
        /** post properties */
        var propertyPayload = JSON.stringify({
            LightSwitch: 1
        });

        device.postProps(propertyPayload);
        /** post events */
        lbs_location();
        var eventPayload = JSON.stringify({
            cdma: '0',
            bts: bts,
            nearbts: nearbts
        });

        device.postEvent({
            id: 'LocationInfo',
            params: eventPayload
        });
    }, 6000);
}


var status = net.getStatus();
console.log('net status is: ' + status);

if (status == 'connect') {
    createDevice();
} else {
    net.on('connect', function() {
        console.log('net connect success');
        createDevice();
    });
}
